The Unofficial Newsletter of Delphi Users - by Robert Vivrette


Enabling Controls Using Sets

By Alan G. Lloyd - AlanGLLoyd@aol.com

Another way of enabling a series of controls dependant on particular states, is to use enumerated values to specify the buttons, then using a set of such values and an array of the controls, enable buttons by using the functionality of a property. This involves a small amount of lower level coding but pays dividends in the ease wih which you can code changes to the controls enabling.

Using the buttons of a recorder control as a simple example, the controls would be :-

     RecBtn: TButton;
     PlayBtn: TButton;
     RewindBtn: TButton;
     StopBtn: TButton;
     FFwdBtn: TButton;
1 Declare the enumerated values and a set of such values.
     TMMButton = (mmbRecord, mmbPlay, mmbRewind, mmbStop, mmbFFwd);
     TMMButtonSet = set of TMMButton;
In the form's class declaration ...

2 Declare an array of the controls in the private section of the form class. The Enabled property is introduced into the TControl object (which is the ancestor of most controls) and so this is used as the array type.

     FBtnArray : array[TMMButton] of TControl;
Note the subtle way of declaring an array with indices of all the TMMButton values.

3 Declare a property named EnabledButtons (or whatever) and a specify a write accessor method :-

     property EnabledButtons : TMMButtonSet write SetEnabledButtons;
4 Declare the accessor function :-
     procedure SetEnabledButtons(AValue : TMMButtonSet);
5 In the FormCreate event handler fill the button array appropriately :-
     FBtnArray[mmbRecord] := RecBtn;
     FBtnArray[mmbPlay] := PlayBtn;
     FBtnArray[mmbRewind] := RewindBtn;
     FBtnArray[mmbStop] := StopBtn;
     FBtnArray[mmbFFwd] := FFwdBtn;
6 Code the accessor function to set the buttons enabled as specified in the buttonset. Note that unless you want to read the buttonset it does not need to be stored.
     procedure TForm1.SetEnabledButtons(AValue : TMMButtonSet);
     var
       I : TMMButton;
     begin
       for I := Low(TMMButton) to High(TMMButton) do
         FBtnArray[I].Enabled := (I in AValue);
     end;
Now comes the easy part - in your operating code enable buttons with code such as :-
     EnabledButtons := [mmbRewind, mmbStop, mmbFFwd];
Short, simple, clear operating code.

This can be extended to other properties of controls such a visibility, glyphs, colours, positions, etc.